//
//  MoneyString.m
//  投融保
//
//  Created by 523 on 14-1-10.
//  Copyright (c) 2014年 木叶科技. All rights reserved.
//

#import "MoneyString.h"

@implementation MoneyString

+ (NSString *)moneyStringWithDigitStr:(NSString *)digitString
{
    NSLog(@"The begin string:%@",digitString);
    NSArray *datas = [NSArray arrayWithObjects:@"零", @"壹", @"贰", @"叁", @"肆", @"伍", @"陆", @"柒", @"捌", @"玖", nil];
    NSArray *infos = [NSArray arrayWithObjects:@"元", @"拾", @"佰", @"仟", @"万", @"拾", @"佰", @"仟", @"亿", @"拾", @"佰", @"仟", @"万", nil];
    
    NSMutableString *processString = [[NSMutableString alloc] initWithString:digitString];
    
    // creat a new mutable string
    NSMutableString *resultString = [NSMutableString string];
    int i = 0;
    int j = processString.length;
    
    // str:165047523
    // 1亿 6仟 5佰 0拾 4万 7仟 5佰 2拾 3分 ——> 壹亿 陆仟 伍佰 零拾 肆万 柒仟 伍佰 贰拾 叁分
    
    while (processString.length != 0) {
        
        // Add location tags after each number
        [resultString insertString:[infos objectAtIndex:i] atIndex:0];
        i++;
        
        // Obtain a character (a number), then the number corresponding uppercase characters restructuring to the ‘resultString’
        j--;
        NSString *specifiedNumberStrAtIndex = [processString substringWithRange:NSMakeRange(j, 1)];
        int specifiedNumber = [specifiedNumberStrAtIndex intValue];
        
        int number = specifiedNumber % 10;
        
        [resultString insertString:[datas objectAtIndex:number] atIndex:0];
        
        // Delete of a character, so that the next time through the loop with
        [processString deleteCharactersInRange:NSMakeRange(j, 1)];
        
        NSLog(@"resultString = %@",resultString);
    }
    
    NSString *moneyString = [NSString stringWithFormat:@"%@",resultString];
    
    // To use regular expressions to replace specific characters
    NSError *error=nil;
    NSArray *expressions = [NSArray arrayWithObjects:@"零[拾佰仟]", @"零+亿", @"零+万", @"零+元", @"零+",@"亿万",nil];
    NSArray *changes = [NSArray arrayWithObjects:@"零", @"亿",@"万",@"",@"零",@"亿",nil];
    
    for (int k = 0; k < 6; k++)
    {
        NSRegularExpression *reg=[[NSRegularExpression alloc] initWithPattern:[expressions objectAtIndex:k] options:NSRegularExpressionCaseInsensitive error:&error];
        
        moneyString = [reg stringByReplacingMatchesInString:moneyString options:0 range:NSMakeRange(0, moneyString.length) withTemplate:[changes objectAtIndex:k]];
        
        NSLog(@"moneyString = %@",moneyString);
    }
    return moneyString;
    
}


@end
